package utils

import (
	"fmt"
	"os"
	"path/filepath"
	consts "qrsj-assistant/backend/const"
	"qrsj-assistant/backend/types"

	jsoniter "github.com/json-iterator/go"
)

func FileInit() {
	configAppPath := InitConfigPath()
	fullAppPath := filepath.Join(configAppPath, consts.CONFIG_FILE_NAME)
	exists := FileExists(fullAppPath)
	conf := types.ConfigApp{}
	fmt.Println(exists)
	fmt.Println(conf)
}

func InitConfigPath() string {
	configAppPath := GetConfigAppPath()
	os.MkdirAll(configAppPath, 0755)
	return configAppPath
}

func FileExists(filename string) bool {
	info, err := os.Stat(filename)
	if os.IsNotExist(err) {
		return false
	}
	return !info.IsDir()
}

func GetConfigAppPath() string {
	homeDir, _ := os.UserHomeDir()
	configPath := filepath.Join(homeDir, "AppData", "Roaming", "qrsj-assistant", "config")
	return configPath
}

func WriteFile(filename string, data []byte) error {
	return os.WriteFile(filename, data, 0644)
}

func ReadFile(filename string) ([]byte, error) {
	return os.ReadFile(filename)
}

// 读取address JSON文件
func ReadAddressJSON(json jsoniter.API, addressInfo *types.AddressFile) {
	path := GetBaseAddressPath()
	data, err := os.ReadFile(path)
	if err != nil {
		fmt.Printf("读取文件错误 err=%v\n", err)
		return
	}
	err = json.Unmarshal(data, addressInfo)
	if err != nil {
		fmt.Printf("反序列化错误 err=%v\n", err)
		return
	}
}

// 更新address JSON文件
func UpdateAddressJSON(json jsoniter.API, newAddressInfo *types.AddressFile) {
	path := GetBaseAddressPath()
	data, err := json.MarshalIndent(newAddressInfo, "", "  ")
	if err != nil {
		fmt.Printf("序列化错误 err=%v\n", err)
		return
	}
	err = WriteFile(path, data)
	if err != nil {
		fmt.Printf("写入文件错误 err=%v\n", err)
		return
	}
}

func GetBaseAddressPath() string {
	// 获取当前目录
	dir, _ := os.Getwd()
	path := filepath.Join(dir, "config", "base_address.json")
	return path
}
